package com.b2c.erp.controller;


import com.alibaba.fastjson.JSONObject;
import com.b2c.entity.result.PagingResponse;
import com.b2c.common.utils.DateUtil;
import com.b2c.entity.ErpOrderItemEntity;
import com.b2c.entity.ExpressEntity;
import com.b2c.entity.SysVariableEntity;
import com.b2c.entity.ErpOrderEntity;
import com.b2c.entity.erp.enums.ErpOrderSourceEnum;
import com.b2c.entity.erp.vo.ErpOrderItemListVo;
import com.b2c.entity.erp.vo.PrintImgVo;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.entity.enums.EnumUserActionType;
import com.b2c.interfaces.ExpressCompanyService;
import com.b2c.interfaces.erp.ErpOrderService;
import com.b2c.interfaces.erp.ErpUserActionLogService;
import com.b2c.interfaces.erp.ExpressService;
import com.b2c.erp.DataConfigObject;
import com.b2c.entity.enums.EnumErpOrderSendStatus;
import com.b2c.erp.kuaidi100.ExpressPrintResult;
import com.b2c.erp.kuaidi100.ExpressPrintUtils;
import com.b2c.erp.kuaidi100.SendVo;
import com.b2c.entity.vo.order.OrderWaitSendListVo;

import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
* 描述：
* 订单Controller
*
* @author qlp
* @date 2019-06-03 10:47
*/
@RequestMapping("/order")
@Controller
public class OrderController {
   @Autowired
   private ErpOrderService orderService;
   @Autowired
   private ExpressService expressService;

   @Autowired
   private ExpressCompanyService expressCompanyService;
   @Autowired
   private ErpUserActionLogService logService;

   Logger log = LoggerFactory.getLogger(OrderController.class);

   /***
    * 订单列表
    * @param model
    * @param request
    * @return
    */
   @RequestMapping(value = "/list", method = RequestMethod.GET)
   public String orderList(Model model, HttpServletRequest request) {
       Integer pageIndex = 1;
       Integer pageSize = DataConfigObject.getInstance().getPageSize();

       if (StringUtils.isEmpty(request.getParameter("page")) == false) {
           try {
               pageIndex = Integer.parseInt(request.getParameter("page"));
           } catch (Exception e) {
           }
       }
       String searchUrl = "/order/list";
       model.addAttribute("searchUrl", searchUrl);
       Integer saleType = null;
       if(!StringUtils.isEmpty(request.getParameter("saleType"))){
           try{
               saleType = Integer.parseInt(request.getParameter("saleType"));
               model.addAttribute("saleType",saleType);
           }catch (Exception e){}
       }

       String orderNum = request.getParameter("orderNum");
       model.addAttribute("orderNum", orderNum);

       String mobile = request.getParameter("mobile");
       model.addAttribute("mobile", mobile);

       String logisticsCode = request.getParameter("logisticsCode");
       model.addAttribute("logisticsCode", logisticsCode);

       Integer startTime = 0;

       if (StringUtils.isEmpty(request.getParameter("startTime")) == false) {
           startTime = DateUtil.dateToStamp(request.getParameter("startTime"));
           model.addAttribute("startTime", request.getParameter("startTime"));
       }

       Integer endTime = 0;

       if (StringUtils.isEmpty(request.getParameter("endTime")) == false) {
           endTime = DateUtil.dateTimeToStamp(request.getParameter("endTime") + " 23:59:59");
           model.addAttribute("endTime", request.getParameter("endTime"));
       }


       model.addAttribute("pageIndex", pageIndex);
       model.addAttribute("pageSize", pageSize);

       PagingResponse<OrderWaitSendListVo> result = orderService.getWaitSendOrderList(pageIndex, pageSize, null, orderNum, mobile, logisticsCode, startTime, endTime,saleType,null);

       model.addAttribute("list", result.getList());
       model.addAttribute("totalSize", result.getTotalSize());

       model.addAttribute("company", expressCompanyService.getExpressCompany());

       model.addAttribute("view", "order_list");
       model.addAttribute("pView", "sale");
       model.addAttribute("ejcd", "销售");
       model.addAttribute("sjcd", "订单查询");
       return "order_list";
   }

   /***
    * 订单商品列表
    * @param model
    * @param request
    * @return
    */
   @RequestMapping(value = "/item_list", method = RequestMethod.GET)
   public String orderItemList(Model model, HttpServletRequest request) {
       Integer pageIndex = 1;
       Integer pageSize = DataConfigObject.getInstance().getPageSize();

       if (StringUtils.isEmpty(request.getParameter("page")) == false) {
           try {
               pageIndex = Integer.parseInt(request.getParameter("page"));
           } catch (Exception e) {
           }
       }
       String searchUrl = "/order/item_list";
       model.addAttribute("searchUrl", searchUrl);

       String orderNum = request.getParameter("orderNum");
       model.addAttribute("orderNum", orderNum);

//        String goodsNum = request.getParameter("goodsNum");
//        model.addAttribute("goodsNum", goodsNum);

       String skuNum = request.getParameter("skuNum");
       model.addAttribute("skuNum", skuNum);
       Integer orderStatus = null;
       if(!StringUtils.isEmpty(request.getParameter("orderStatus"))){
           try{
               orderStatus = Integer.parseInt(request.getParameter("orderStatus"));
//                model.addAttribute("saleType",saleType);
           }catch (Exception e){}
       }

       Integer startTime = 0;

       if (StringUtils.isEmpty(request.getParameter("startTime")) == false) {
           startTime = DateUtil.dateToStamp(request.getParameter("startTime"));
           model.addAttribute("startTime", request.getParameter("startTime"));
       }

       Integer endTime = 0;

       if (StringUtils.isEmpty(request.getParameter("endTime")) == false) {
           endTime = DateUtil.dateTimeToStamp(request.getParameter("endTime") + " 23:59:59");
           model.addAttribute("endTime", request.getParameter("endTime"));
       }


       model.addAttribute("pageIndex", pageIndex);
       model.addAttribute("pageSize", pageSize);

       PagingResponse<ErpOrderItemListVo> result = orderService.getOrderItemList(pageIndex, pageSize, orderNum,skuNum, startTime, endTime,orderStatus);

       model.addAttribute("list", result.getList());
       model.addAttribute("totalSize", result.getTotalSize());

       model.addAttribute("view", "order_item_list");
       model.addAttribute("pView", "sale");
       model.addAttribute("ejcd", "销售");
       model.addAttribute("sjcd", "订单查询");
       return "order/order_item_list";
   }


   /***
    * 拣货中订单list
    * @param model
    * @param request
    * @return
    */
   @RequestMapping(value = "/order_picking_list", method = RequestMethod.GET)
   public String getOrderPickingList(Model model, HttpServletRequest request) {
       Integer pageIndex = 1;
       Integer pageSize = DataConfigObject.getInstance().getPageSize();
       ;
       if (StringUtils.isEmpty(request.getParameter("page")) == false) {
           try {
               pageIndex = Integer.parseInt(request.getParameter("page"));
           } catch (Exception e) {
           }
       }

       String orderNum = "";
       String mjMobile = "";
       String logisticsCode = "";
       Integer startTime = 0;
       Integer endTime = 0;
       if (!StringUtils.isEmpty(request.getParameter("orderNum"))) {
           orderNum = request.getParameter("orderNum");
       }
       if (!StringUtils.isEmpty(request.getParameter("mjMobile"))) {
           mjMobile = request.getParameter("mjMobile");
       }
       if (!StringUtils.isEmpty(request.getParameter("logisticsCode"))) {
           logisticsCode = request.getParameter("logisticsCode");
       }
       if (!StringUtils.isEmpty(request.getParameter("startTime"))) {
           startTime = DateUtil.dateToStamp(request.getParameter("startTime"));
       }
       if (!StringUtils.isEmpty(request.getParameter("endTime"))) {
           endTime = DateUtil.dateToStamp(request.getParameter("endTime" + " 23:59:59"));
       }

       model.addAttribute("pageIndex", pageIndex);
       model.addAttribute("pageSize", pageSize);

       PagingResponse<OrderWaitSendListVo> result = orderService.getWaitSendOrderList(pageIndex, pageSize, EnumErpOrderSendStatus.Picking, orderNum, mjMobile, logisticsCode, startTime, endTime,null,null);

       model.addAttribute("lists", result.getList());
       model.addAttribute("totalSize", result.getTotalSize());

       model.addAttribute("company", expressCompanyService.getExpressCompany());

//        model.addAttribute("view", "picking_order");
//        model.addAttribute("pView", "ck/order/order_wait_send_list");
//        model.addAttribute("ejcd", "销售");
//        model.addAttribute("sjcd", "拣货中订单");


       model.addAttribute("view", "picking_order");
       model.addAttribute("pView", "ck");
       model.addAttribute("ejcd", "销售");
       model.addAttribute("sjcd", "拣货中订单");
       model.addAttribute("pageTitle", "拣货中订单");


//        return "order_picking_list";
       return "order_wait_pick_list";
   }

   /***
    * 待发货订单列表
    * @param model
    * @param request
    * @return
    */
   @RequestMapping(value = "/order_wait_send_list", method = RequestMethod.GET)
   public String getOrderStockOutList(Model model, HttpServletRequest request) {
       Integer pageIndex = 1;
       Integer pageSize = DataConfigObject.getInstance().getPageSize();

       if (StringUtils.isEmpty(request.getParameter("page")) == false) {
           try {
               pageIndex = Integer.parseInt(request.getParameter("page"));
           } catch (Exception e) {
           }
       }
       String searchUrl = "/order/order_wait_send_list";
       model.addAttribute("searchUrl", searchUrl);


       String orderNum = request.getParameter("orderNum");
       model.addAttribute("orderNum", orderNum);

       String mobile = request.getParameter("mobile");
       model.addAttribute("mobile", mobile);

       String logisticsCode = request.getParameter("logisticsCode");
       model.addAttribute("logisticsCode", logisticsCode);

       Integer startTime = 0;

       if (StringUtils.isEmpty(request.getParameter("startTime")) == false) {
           startTime = DateUtil.dateToStamp(request.getParameter("startTime"));
           model.addAttribute("startTime", request.getParameter("startTime"));
       }

       Integer endTime = 0;

       if (StringUtils.isEmpty(request.getParameter("endTime")) == false) {
           endTime = DateUtil.dateTimeToStamp(request.getParameter("endTime") + " 23:59:59");
           model.addAttribute("endTime", request.getParameter("endTime"));
       }


       model.addAttribute("pageIndex", pageIndex);
       model.addAttribute("pageSize", pageSize);

       PagingResponse<OrderWaitSendListVo> result = orderService.getWaitSendOrderList(pageIndex, pageSize, EnumErpOrderSendStatus.Picked, orderNum, mobile, logisticsCode, startTime, endTime,null,null);

       model.addAttribute("list", result.getList());
       model.addAttribute("totalSize", result.getTotalSize());

       model.addAttribute("company", expressCompanyService.getExpressCompany());

       model.addAttribute("view", "wait_send_order");
       model.addAttribute("pView", "ck");
       model.addAttribute("ejcd", "销售");
       model.addAttribute("sjcd", "待发货订单");
       return "order_wait_send_list";
   }


   /**
    * 已发货订单
    *
    * @param model
    * @param request
    * @return
    */
   @RequestMapping(value = "/order_has_send_list", method = RequestMethod.GET)
   public String getOrderHasSendList(Model model, HttpServletRequest request) {
       Integer pageIndex = 1;
       Integer pageSize = DataConfigObject.getInstance().getPageSize();
       ;
       if (StringUtils.isEmpty(request.getParameter("page")) == false) {
           try {
               pageIndex = Integer.parseInt(request.getParameter("page"));
           } catch (Exception e) {
           }
       }
       String searchUrl = "/order/order_has_send_list";
       model.addAttribute("searchUrl", searchUrl);

       String orderNum = request.getParameter("orderNum");
       model.addAttribute("orderNum", orderNum);

       String mobile = request.getParameter("mobile");
       model.addAttribute("mobile", mobile);

       String logisticsCode = request.getParameter("logisticsCode");
       model.addAttribute("logisticsCode", logisticsCode);

       Integer startTime = 0;

       if (StringUtils.isEmpty(request.getParameter("startTime")) == false) {
           startTime = DateUtil.dateToStamp(request.getParameter("startTime"));
           model.addAttribute("startTime", request.getParameter("startTime"));
       }

       Integer endTime = 0;

       if (StringUtils.isEmpty(request.getParameter("endTime")) == false) {
           endTime = DateUtil.dateTimeToStamp(request.getParameter("endTime") + " 23:59:59");
           model.addAttribute("endTime", request.getParameter("endTime"));
       }


       model.addAttribute("pageIndex", pageIndex);
       model.addAttribute("pageSize", pageSize);

       PagingResponse<OrderWaitSendListVo> result = orderService.getWaitSendOrderList(pageIndex, pageSize, EnumErpOrderSendStatus.HasSend, orderNum, mobile, logisticsCode, startTime, endTime,null,null);

       model.addAttribute("list", result.getList());
       model.addAttribute("totalSize", result.getTotalSize());


       model.addAttribute("status", EnumErpOrderSendStatus.HasSend.getIndex());

       model.addAttribute("view", "is_send_order");
       model.addAttribute("pView", "ck");
       model.addAttribute("ejcd", "销售");
       model.addAttribute("sjcd", "已发货订单");
       return "order_wait_send_list";
   }

   /***
    * 订单发货单（打印页面）
    * @param model
    * @param request
    * @return
    */
   @RequestMapping(value = "/order_send_invoice", method = RequestMethod.GET)
   public String getInvoiceSendDetail(Model model, HttpServletRequest request, @RequestParam Long id) {
       //查询订单信息
       var order = orderService.getOrderEntityById(id);

       if (order != null) {
           model.addAttribute("order", order);
           List<ErpOrderItemListVo> orderItems = orderService.getErpOrderItemsByOrderId(id);
           model.addAttribute("orderGoods", orderItems);
       }
       return "order_send_invoice";
   }


   /***
    * 快递面单打印（打印页面）
    * @param model
    * @param request
    * @return
    */
   @RequestMapping(value = "/order_send_express", method = RequestMethod.GET)
   public String orderSendExpress(Model model, HttpServletRequest request) {
       Long id =Long.valueOf(request.getParameter("id"));
       Integer expressId=Integer.parseInt(request.getParameter("express"));
       //查询单据
       ErpOrderEntity order = orderService.getOrderEntityById(id);

       //判断是否有打印过
//        if(order.getLogisticsPrintStatus().intValue() == EnumErpOrderlogisticsPrintStatus.Printed.getIndex()){
//            //已经打印过
//
//        }

       //查询是否已经打印过，打印过有保存快递面单信息
       ExpressEntity express = expressService.getExpress(order.getOrder_num());
       if (null != express) {
           model.addAttribute("img", express.getSendPrintImg());
           model.addAttribute("error", "快递单号：" + express.getSendCode());
       } else {

           if (null == express && order.getStatus() == EnumErpOrderSendStatus.HasOut.getIndex()) {
               //查询系统收货地址
               SysVariableEntity sendAddress = null;//systemService.getVariable(VariableEnums.DEFAULT_SEND_ADDRESS.name());
               SendVo sendVo = new SendVo();
               if (sendAddress == null) {
                   sendVo.setSendManMobile("400-800-1713");
                   sendVo.setSendManName("华衣云购");
                   sendVo.setSendManPrintAddr("广东省东莞市大朗镇聚新二路42号");
                   log.error("系统没有配置默认发货地址");
               } else
                   sendVo = JSONObject.parseObject(sendAddress.getValue(), SendVo.class);
               //添加系统日志
               logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Query,
                       "/order/order_send_express?id=" + id, "订单发货单（打印页面） , 日期 : " + new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()), "成功");


               PrintImgVo print = new PrintImgVo();
               //发件人信息
               print.setSendManName(sendVo.getSendManName());
               print.setSendManMobile(sendVo.getSendManMobile());
               print.setSendManPrintAddr(sendVo.getSendManPrintAddr());

               //收件人信息
               print.setRecManName(order.getContactPerson());
               print.setRecManMobile(order.getMobile());

               String province = "";
               String city = "";
               String area = "";
               if (StringUtils.isEmpty(order.getProvince()) == false) {
                   province = order.getProvince();
               }
               if (StringUtils.isEmpty(order.getCity()) == false) {
                   city = order.getCity();
               }
               if (StringUtils.isEmpty(order.getArea()) == false) {
                   area = order.getArea();
               }
               print.setRecManProvince(province);
               print.setRecManCity(city);
               print.setRecManDistrict(area);

               print.setRecManAddr(order.getAddress());
               print.setRecManPrintAddr(province + city + area + order.getAddress());//province + city + area + order.getAddress()

               //组合订单商品数据
               //StringBuilder orderGoods = new StringBuilder();
               //orderGoods.append("\r\n");
               var orderItems = orderService.getErpOrderItemsByOrderId(id);

               StringBuilder orderDetail=new StringBuilder("单号").append(order.getOrder_num()).append("。");
               Integer goodCount=0;
               for (var item:orderItems) {
                   //orderGoods.append(item.getProductMallName());
                   //orderGoods.append("[数量："+item.getQuantity()+"]");
                   //orderGoods.append("\r\n");
                   orderDetail.append(item.getSpecNumber()).append(",");
                   orderDetail.append(item.getColorValue()).append(item.getSizeValue());
                   orderDetail.append(item.getQuantity()).append("件");
                   goodCount+=item.getQuantity().intValue();
               }
               //订单信息
               //orderDetail += orderGoods.toString();
               print.setNet("cainiao");
               print.setCargo(orderDetail.toString());//order.getOrderDetail()
               if(expressId.intValue()==1){
                   print.setKuaidicomname("韵达快递");
                   print.setKuaidicom("yunda");
               }else if(expressId.intValue()==2){
                   print.setKuaidicomname("百世快递");
                   print.setKuaidicom("huitongkuaidi");
               }

               print.setOrderId(order.getOrder_num());
               print.setRemark("订单备注");
               //快递信息
               print.setCount(goodCount);//件数
               print.setWeight(0.25d);//物品总重量KG
               print.setVolumn(2000d);//物品总体积，CM*CM*CM，double类
//            String img = expressService.printImg(print);

               SysVariableEntity sysVariableEntity = null;// systemService.getVariable(VariableEnums.URL_WMS_INDEX.name());
               print.setPollCallBackUrl(sysVariableEntity.getValue());

               int openSubscription = 0;
               if (order.getSource().equalsIgnoreCase(ErpOrderSourceEnum.YUNGOU.getIndex())) {
                   openSubscription = 1;
               }
               String partnerId="4398900340329";
               String partnerKey="dFVsaGlNYW1LdU0yMkx1bHR5OVJHTFJDMjdPeThSLyt1ckVNMHNDMnFjaW1VdC9Rd3doNE5wYVVsSTVHTWpqaw==";
               try {
                   Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
                   partnerId =properties.getProperty("partnerId");
                   partnerKey =properties.getProperty("partnerKey");
               } catch (Exception e) {
               }

               //请求接口打印快递面单
               ResultVo<ExpressPrintResult> resultVo = ExpressPrintUtils.generateExpressPrintImg(print, openSubscription,partnerId,partnerKey);

               if (resultVo.getCode() == EnumResultVo.SUCCESS.getIndex()) {
                   //更新快递面单信息
                   expressService.printExpress(order.getId(), resultVo.getData().getKuaidicomName(), resultVo.getData().getKuaidicom(), resultVo.getData().getKuaidinum(), resultVo.getData().getImgBase64());

                   model.addAttribute("img", resultVo.getData().getImgBase64());
               } else {
                   model.addAttribute("error", resultVo.getMsg());
               }
           } else {
               model.addAttribute("error", "订单还没有出库，不能打印快递单");
           }
       }
       return "stock_out_order_send_express";
   }

//    @RequestMapping(value = "/test_express_info", method = RequestMethod.GET)
//    public String test() {
//        String strs = "{\"status\":\"abort\",\"billstatus\":\"\",\"message\":\"3天查询无记录\",\"autoCheck\":\"0\",\"comOld\":\"\",\"comNew\":\"\",\"lastResult\":{\"message\":\"快递公司参数异常：单号不存在或者已经过期\",\"nu\":\"safasdfa\",\"ischeck\":\"0\",\"condition\":\"\",\"com\":\"yunda\",\"status\":\"201\",\"state\":\"0\",\"data\":[]}}";
//        JSONObject obj = JSONObject.parseObject(strs);
//        expressService.updExpressInfo(obj);
//        return "";
//    }

   @RequestMapping(value = "/order_send_express_hebing", method = RequestMethod.GET)
   public String orderSendExpressHeBing(Model model, HttpServletRequest request) {
       String orderIds = request.getParameter("ids");
       //查询单据
       List<ErpOrderEntity> orderList = orderService.getOrderEntityByIds(orderIds);
       if(orderList==null) model.addAttribute("error", "参数错误：没有找到选中的订单");
       for (var order:orderList) {
           if(order.getStatus() != EnumErpOrderSendStatus.HasOut.getIndex()){
               model.addAttribute("error", "参数错误：订单"+order.getOrder_num()+"状态不是已出库状态，不能打单发货");
               return "stock_out_order_send_express";
           }
       }
       /*****开始打单******/

       //查询系统收货地址
       SysVariableEntity sendAddress = null;// systemService.getVariable(VariableEnums.DEFAULT_SEND_ADDRESS.name());
       SendVo sendVo = new SendVo();
       if (sendAddress == null) {
           sendVo.setSendManMobile("400-800-1713");
           sendVo.setSendManName("华衣云购");
           sendVo.setSendManPrintAddr("广东省东莞市大朗镇聚新二路42号");
           log.error("系统没有配置默认发货地址");
       } else
           sendVo = JSONObject.parseObject(sendAddress.getValue(), SendVo.class);



       PrintImgVo print = new PrintImgVo();
       //发件人信息
       print.setSendManName(sendVo.getSendManName());
       print.setSendManMobile(sendVo.getSendManMobile());
       print.setSendManPrintAddr(sendVo.getSendManPrintAddr());

       //收件人信息
       print.setRecManName(orderList.get(0).getContactPerson());
       print.setRecManMobile(orderList.get(0).getMobile());

       String province = "";
       String city = "";
       String area = "";
       if (StringUtils.isEmpty(orderList.get(0).getProvince()) == false) {
           province = orderList.get(0).getProvince();
       }
       if (StringUtils.isEmpty(orderList.get(0).getCity()) == false) {
           city = orderList.get(0).getCity();
       }
       if (StringUtils.isEmpty(orderList.get(0).getArea()) == false) {
           area = orderList.get(0).getArea();
       }
       print.setRecManProvince(province);
       print.setRecManCity(city);
       print.setRecManDistrict(area);

       print.setRecManAddr(orderList.get(0).getAddress());
       print.setRecManPrintAddr(province + city + area + orderList.get(0).getAddress());


       //订单信息
       String orderDetail = "订单："+orderList.get(0).getOrder_num()+"等"+orderList.size()+"个订单";
//        for (var order:orderList) {
//            orderDetail += "订单：" + order.getOrder_num()+"\r\n";
//        }

       print.setNet("cainiao");
       print.setCargo(orderDetail);//order.getOrderDetail()
       print.setKuaidicomname("韵达快递");
       print.setKuaidicom("yunda");
       print.setOrderId(orderList.get(0).getOrder_num());
       print.setRemark("订单备注");
       //快递信息
       print.setCount(orderList.size());//件数
       print.setWeight(0.25d);//物品总重量KG
       print.setVolumn(2000d);//物品总体积，CM*CM*CM，double类
//            String img = expressService.printImg(print);

       SysVariableEntity sysVariableEntity = null;//systemService.getVariable(VariableEnums.URL_WMS_INDEX.name());
       print.setPollCallBackUrl(sysVariableEntity.getValue());

       int openSubscription = 0;

       String partnerId="4398900340329";
       String partnerKey="dFVsaGlNYW1LdU0yMkx1bHR5OVJHTFJDMjdPeThSLyt1ckVNMHNDMnFjaW1VdC9Rd3doNE5wYVVsSTVHTWpqaw==";
       try {
           Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
           partnerId =properties.getProperty("partnerId");
           partnerKey =properties.getProperty("partnerKey");
       } catch (Exception e) {
       }

       //请求接口打印快递面单
       ResultVo<ExpressPrintResult> resultVo = ExpressPrintUtils.generateExpressPrintImg(print, openSubscription,partnerId,partnerKey);

       if (resultVo.getCode() == EnumResultVo.SUCCESS.getIndex()) {

           for (var order:orderList) {
               //更新快递面单信息
               expressService.printExpress(order.getId(), resultVo.getData().getKuaidicomName(), resultVo.getData().getKuaidicom(), resultVo.getData().getKuaidinum(), resultVo.getData().getImgBase64());
               //更新订单状态已发货
               orderService.sendOrder(order.getId());
           }


           model.addAttribute("img", resultVo.getData().getImgBase64());
       } else {
           model.addAttribute("error", resultVo.getMsg());
       }


       /*****结束打单******/

       return "stock_out_order_send_express";
   }


   /**
    * 订单出库（发货）
    *
    * @param model
    * @param request
    * @return
    */
   @RequestMapping(value = "/order_send", method = RequestMethod.GET)
   public String getOrderSend(Model model, HttpServletRequest request) {
       ErpOrderEntity order = null;

       if (StringUtils.isEmpty(request.getParameter("id")) == false) {
           try {
               Long id = Long.parseLong(request.getParameter("id"));
               order = orderService.getOrderEntityById(id);
           } catch (Exception e) {
           }
       }

       if (StringUtils.isEmpty(request.getParameter("number")) == false && order == null) {
           //没有查到order 并且number参数不为空
           order = orderService.getOrderEntityByNum(request.getParameter("number"));
       }

       if (order != null) {
           model.addAttribute("order", order);
           //查询订单明细
           var items = orderService.getErpOrderItemsByOrderId(order.getId());
           model.addAttribute("orderItems", items);
       }


       return "order_send";
   }

   /**
    * 订单商品列表
    *
    * @param model
    * @param request
    * @param id
    * @return
    */
   @RequestMapping(value = "/order_goods_list", method = RequestMethod.GET)
   public String orderGoodsList(Model model, HttpServletRequest request, @RequestParam Long id) {
       //查询订单信息
       var order = orderService.getOrderEntityById(id);

       if (order != null) {
           model.addAttribute("order", order);
           List<ErpOrderItemListVo> orderItems = orderService.getErpOrderItemsByOrderId(id);
           model.addAttribute("orderGoods", orderItems);
        
       }
       return "order_goods_list";
   }

//    /**
//     * 批量预览拣货单GET
//     *
//     * @param model
//     * @param request
//     * @return
//     */
//    @RequestMapping(value = "/order_pick_goods_review", method = RequestMethod.GET)
//    public String generatingPickingListGet(Model model, HttpServletRequest request) {
//        return "redirect:/order_delivery/wait_pick_order_list";
//    }
//    /**
//     * 批量预览拣货单
//     *
//     * @param model
//     * @param request
//     * @return
//     */
//    @RequestMapping(value = "/order_pick_goods_review", method = RequestMethod.POST)
//    public String generatingPickingList(Model model, HttpServletRequest request) {
//        log.info("生产拣货单预览，订单："+ JSON.toJSONString(request.getParameterValues("ids")));
//        String[] ids = request.getParameterValues("ids");
//        if (ids != null && ids.length > 0) {
//            List<Long> orderIds = new ArrayList<>();
//            for (String id : ids) {
//                orderIds.add(Long.parseLong(id));
//            }
//            List<FaHuoDaiJianHuoGoodsVo> list = orderService.getDaiJianHuoOrderItemGoodsListAndDistinctSku(orderIds);
//            model.addAttribute("goodsList", list);
//            model.addAttribute("orderCount", ids.length);
//            model.addAttribute("ids", JSON.toJSONString(orderIds));
//            model.addAttribute("skuCount", list.size());
//        }
//
//        model.addAttribute("view", "djhorder");
//        model.addAttribute("pView", "ck");
//        model.addAttribute("ejcd", "销售");
//        model.addAttribute("sjcd", "待拣货订单");
////        return "order_pick_goods_review_list1";//新版本
//        return "order_pick_goods_review_list";
//    }


   /**
    * 订单导出
    *
    * @param request
    * @param response
    */
   @RequestMapping(value = "/order_has_send_export", method = {RequestMethod.POST, RequestMethod.GET})
   @ResponseBody
   public void outExport(HttpServletRequest request, HttpServletResponse response) {
       Integer startTime = 0;
       Integer endTime = 0;
       if (!StringUtils.isEmpty(request.getParameter("startTime"))) {
           startTime = DateUtil.dateToStamp(request.getParameter("startTime"));
       }
       if (!StringUtils.isEmpty(request.getParameter("endTime"))) {
           String endDateStr = request.getParameter("endTime") + " 23:59:59";
           endTime = DateUtil.dateTimeToStamp(endDateStr);
       }
       //按条件搜索
       var orderList = orderService.getErporderItemSendList(startTime, endTime);

       /***************根据店铺查询订单导出的信息*****************/
       String excelFileName = "";//excel文件名前缀

       //创建Excel工作薄对象
       HSSFWorkbook workbook = new HSSFWorkbook();

       //创建Excel工作表对象
       HSSFSheet sheet = workbook.createSheet();
       HSSFRow row = null;
       HSSFCell cell = null;
       //第一行为空
       row = sheet.createRow(0);

       cell = row.createCell(0);
       cell.setCellValue("ID");

       cell = row.createCell(1);
       cell.setCellValue("订单号");

       cell = row.createCell(2);
       cell.setCellValue("下单时间");

       cell = row.createCell(3);
       cell.setCellValue("发货时间");

       cell = row.createCell(4);
       cell.setCellValue("商品编码");

       cell = row.createCell(5);
       cell.setCellValue("商品数量");

       cell = row.createCell(6);
       cell.setCellValue("SKU");

       cell = row.createCell(7);
       cell.setCellValue("收货人");

       cell = row.createCell(8);
       cell.setCellValue("手机号");

       cell = row.createCell(9);
       cell.setCellValue("地址");

       cell = row.createCell(10);
       cell.setCellValue("物流公司");

       cell = row.createCell(11);
       cell.setCellValue("物流单号");

       cell = row.createCell(12);
       cell.setCellValue("订单来源");

       cell = row.createCell(13);
       cell.setCellValue("销售类型");

       cell = row.createCell(14);
       cell.setCellValue("状态");


       int currRowNum = 0;
       // 循环写入数据
       for (int i = 0; i < orderList.size(); i++) {
           currRowNum++;
           //写入订单
           ErpOrderItemListVo orderVo = orderList.get(i);

           //创建行
           row = sheet.createRow(currRowNum);

           //订单编号
           cell = row.createCell(0);
           cell.setCellValue(orderVo.getOrderId());

           //订单编号
           cell = row.createCell(1);
           cell.setCellValue(orderVo.getOrderNum());

           //下单时间
           cell = row.createCell(2);
           cell.setCellValue(!StringUtils.isEmpty(orderVo.getOrderTime()) ? DateUtil.unixTimeStampToDate(orderVo.getOrderTime()) : "");

           //发货时间
           cell = row.createCell(3);
           cell.setCellValue(!StringUtils.isEmpty(orderVo.getDeliveryTime()) ? DateUtil.unixTimeStampToDate(orderVo.getDeliveryTime()) : "");

           //商品编码
           cell = row.createCell(4);
           cell.setCellValue(orderVo.getProductNumber());

           //商品数量
           cell = row.createCell(5);
           cell.setCellValue(orderVo.getQuantity());

           //sku
           cell = row.createCell(6);
           cell.setCellValue(orderVo.getSkuNumber());

           //收货人
           cell = row.createCell(7);
           cell.setCellValue(orderVo.getContactPerson());
           //手机号
           cell = row.createCell(8);
           cell.setCellValue(orderVo.getContactPerson());
           //地址
           cell = row.createCell(9);
           cell.setCellValue(orderVo.getAddress());

           //物流公司
           cell = row.createCell(10);
           cell.setCellValue(orderVo.getLogisticsCompany());
           //物流单号
           cell = row.createCell(11);
           cell.setCellValue(orderVo.getLogisticsCode());
           //订单来源
           cell = row.createCell(12);
           cell.setCellValue(orderVo.getShopName());

           //销售类型
           cell = row.createCell(13);
           cell.setCellValue((orderVo.getSaleType() == null || orderVo.getSaleType() == 1) ? "实售" : "样品");

           //状态
           cell = row.createCell(14);
           cell.setCellValue(EnumErpOrderSendStatus.getName(orderVo.getStatus()));

       }
       response.reset();
       response.setContentType("application/msexcel;charset=UTF-8");
       try {
           SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
           String date = newsdf.format(new Date());
           response.addHeader("Content-Disposition", "attachment;filename=\""
                   + new String((excelFileName + date + ".xls").getBytes("GBK"),
                   "ISO8859_1") + "\"");
           OutputStream out = response.getOutputStream();
           workbook.write(out);
           out.flush();
           out.close();
       } catch (FileNotFoundException e) {
           JOptionPane.showMessageDialog(null, "导出失败!");
           e.printStackTrace();
       } catch (IOException e) {
           JOptionPane.showMessageDialog(null, "导出失败!");
           e.printStackTrace();
       }

       return;
   }
   @RequestMapping(value = "/douyin_order_view", method = RequestMethod.GET)
   public String purchaseDetail(Model model, HttpServletRequest request) {
       return "/order/douyin_order_view";
   }


   @ResponseBody
   @RequestMapping(value = "/douyin_order_settle_export", method = RequestMethod.GET)
   public void purchasePutDetail(Model model, HttpServletRequest req, HttpServletResponse response) {
       String endTime=req.getParameter("endTime");

       var lists = orderService.douyinOrderSettleExport(req.getParameter("startTime"),endTime);//invoiceService.invoiceItemPOList();

       /***************根据店铺查询订单导出的信息*****************/
       String fileName = "douyin_settle_export_";//excel文件名前缀
       //创建Excel工作薄对象
       HSSFWorkbook workbook = new HSSFWorkbook();

       //创建Excel工作表对象
       HSSFSheet sheet = workbook.createSheet();
       HSSFRow row = null;
       HSSFCell cell = null;
       //第一行为空
       row = sheet.createRow(0);
       cell = row.createCell(0);
       cell.setCellValue("");
       cell = row.createCell(0);
       cell.setCellValue("订单单号");
       cell = row.createCell(1);
       cell.setCellValue("商品编码");
       cell = row.createCell(2);
       cell.setCellValue("规格编码");
       cell = row.createCell(3);
       cell.setCellValue("数量");
       cell = row.createCell(4);
       cell.setCellValue("销售价");
       cell = row.createCell(5);
       cell.setCellValue("采购价");
       cell = row.createCell(6);
       cell.setCellValue("订单时间");


       int currRowNum = 0;
       HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
       // 循环写入数据
       for (int i = 0; i < lists.size(); i++) {
           currRowNum++;
           //写入订单
           ErpOrderItemEntity itemVo = lists.get(i);
           //创建行
           row = sheet.createRow(currRowNum);
           cell = row.createCell(0);
           cell.setCellValue(itemVo.getStockOutNo());
           //商品名称
           cell = row.createCell(1);
           cell.setCellValue(itemVo.getProductNumber());
           cell = row.createCell(2);
           cell.setCellValue(itemVo.getSkuNumber());

           cell = row.createCell(3);
           cell.setCellValue(itemVo.getQuantity());
           //退货单号
           cell = row.createCell(4);
           cell.setCellValue(String.valueOf(itemVo.getItemAmount()));
           //规格
           cell = row.createCell(5);
           cell.setCellValue(String.valueOf(itemVo.getPurPrice()));
           cell = row.createCell(6);
           cell.setCellValue(itemVo.getLocationName());
       }
       response.reset();
       response.setContentType("application/msexcel;charset=UTF-8");
       try {
           SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
           String date = newsdf.format(new Date());
           response.addHeader("Content-Disposition", "attachment;filename=\""
                   + new String((fileName + date + ".xls").getBytes("GBK"),
                   "ISO8859_1") + "\"");
           OutputStream out = response.getOutputStream();
           workbook.write(out);
           out.flush();
           out.close();
       } catch (FileNotFoundException e) {
           JOptionPane.showMessageDialog(null, "导出失败!");
           e.printStackTrace();
       } catch (IOException e) {
           JOptionPane.showMessageDialog(null, "导出失败!");
           e.printStackTrace();
       }
   }
}
